from collections import OrderedDict

from django.contrib.auth.hashers import make_password
from rest_framework import viewsets, mixins
from rest_framework import serializers
import math
from django.http.response import JsonResponse
import json

from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
from rest_framework import status, filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework import viewsets
import jieba
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from goods.models import Product, GoodCategory, GoodBrand, IndexCarouselGood
from goods.serializers import ProductSerializer, GoodCategorySerializer, \
    CarouselGoodSerializer, CategoryBrandAdSerializer, SecondGoodCategorySerializer
from users.models import UserInfo
from utils.permissions import IsOwnerOrReadOnly
from .models import MenuList, RoleList, ReturnGood, ReturnAddress, SystemSet, ReturnReason, Notice, Region
from goods.models import GoodCategory, GoodBrand, Source
from apps.utils.custom_response import CustomPagination
from .serializers import MenuListSerializer, RoleListSerializer, ReturnAddressSerializer, SystemSetSerializer, \
    ReturnReasonSerializer, SuperGoodSerializer, GoodBrandSerializer, SuperGoodCategorySerializer, \
    IndexCarouselGoodSerializer, SuperUserInfoSerializer, NoticeSerializer, ListCarouselGoodSerializer, RegionSerializer
from .filters import MenuFilter, SuperGoodFilter


class NoticeViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication,)
    queryset = Notice.objects.all()
    serializer_class = NoticeSerializer
    pagination_class = CustomPagination


class CustomPaginationRegion(PageNumberPagination):
    """
    最大返回50
    """
    page_size = 100
    page_size_query_param = 'pageSize'
    page_query_param = 'pageNum'
    max_page_size = 50

    def get_paginated_response(self, data):
        info = {
            'code': 200,
            'message': '操作成功',
            'data': OrderedDict([
                ('list', data),
                ('pageNum', self.page.number),
                ('pageSize', self.page.paginator.per_page),
                ('total', self.page.paginator.count),
                ('totalPage', self.page.paginator.num_pages)
            ])
        }
        return Response(info)


class RegionViewSet(viewsets.GenericViewSet, mixins.ListModelMixin):
    queryset = Region.objects.all()
    filterset_fields = ['region_level', 'region_parent_id']  # 精确查找
    serializer_class = RegionSerializer
    pagination_class = CustomPaginationRegion


class UserPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'pageSize'
    page_query_param = 'page'


    def get_paginated_response(self, data):
        info = {
            'code': 200,
            'message': '操作成功',
            'data': OrderedDict([
                ('pageNum', 1),
                ('pageSize', 10),
                ('list', data),
                ('total', self.page.paginator.count),
                ('totalPage', self.page.number)
            ]),

        }
        return Response(info)


class SuperUserListViewSet(ListModelMixin, RetrieveModelMixin, UpdateModelMixin, mixins.DestroyModelMixin,
                           mixins.CreateModelMixin,
                           viewsets.GenericViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = SuperUserInfoSerializer
    pagination_class = UserPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['is_superuser']  # 精确查找

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        info = {
            'code': 200,
            'message': '删除成功',
            'data': []
        }
        return Response(info)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        is_valid = serializer.is_valid()
        if is_valid:
            self.perform_update(serializer)

            if getattr(instance, '_prefetched_objects_cache', None):
                instance._prefetched_objects_cache = {}
            info = {
                'code': 200,
                'message': '操作成功',
                'data': serializer.data
            }
            return Response(info)
        info = {
            'code': 200,
            'message': '操作成功',
            'data': []
        }
        msg = serializer.errors.values()
        info['code'] = 404
        info['message'] = '\n'.join([x[0] for x in msg])
        return Response(info, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        is_valid = serializer.is_valid()
        info = {
            'code': 200,
            'message': '操作成功',
            'data': ''
        }
        if is_valid:
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            info['data'] = serializer.data
            return Response(info, status=status.HTTP_201_CREATED, headers=headers)

        msg = serializer.errors.values()
        info['code'] = 404
        info['message'] = '\n'.join([x[0] for x in msg])
        return Response(info, status=status.HTTP_200_OK)

    def perform_update(self, serializer):
        serializer.validated_data['password'] = make_password(serializer.validated_data['password'], None,
                                                              'pbkdf2_sha256')
        serializer.save()
    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # print(queryset)
    #     page = self.paginate_queryset(queryset)
    #     # print(page)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return self.get_paginated_response(serializer.data)
    #     pageNum = request.query_params.get('pageNum', 1)
    #     pageSize = request.query_params.get('pageSize', 5)
    #     serializer = self.get_serializer(queryset, many=True)
    #     # print(serializer.data)
    #     start = 0 if int(pageNum) == 1 else int(pageNum) - 1
    #     s = start * int(pageSize)
    #     e = (start * int(pageSize)) + int(pageSize)
    #     print(s, e)
    #     data = {
    #         'pageNum': int(pageNum),
    #         'pageSize': int(pageSize),
    #         'totalPage': math.ceil(queryset.count() / int(pageSize)),
    #         'total': queryset.count(),
    #         'list': serializer.data[s:e]
    #     }
    #     return Response({'code': 200, 'message': '操作成功', 'data': data})


class CustomModelMixin(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                       mixins.DestroyModelMixin, mixins.CreateModelMixin, mixins.ListModelMixin,
                       viewsets.GenericViewSet):
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        is_valid = serializer.is_valid()
        info = {
            'code': 200,
            'message': '操作成功',
            'data': ''
        }
        if is_valid:
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            info['data'] = serializer.data
            return Response(info, status=status.HTTP_201_CREATED, headers=headers)
        print(serializer.errors)
        msg = serializer.errors.values()
        info['code'] = 404
        info['message'] = '\n'.join([x[0] for x in msg])
        return Response(info, status=status.HTTP_200_OK)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        info = {
            'code': 200,
            'message': "操作成功",
            'data': serializer.data
        }
        return Response(info)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        is_valid = serializer.is_valid()
        if is_valid:
            self.perform_update(serializer)

            if getattr(instance, '_prefetched_objects_cache', None):
                instance._prefetched_objects_cache = {}
            info = {
                'code': 200,
                'message': '操作成功',
                'data': serializer.data
            }
            return Response(info)
        info = {
            'code': 200,
            'message': '操作成功',
            'data': []
        }
        msg = serializer.errors.values()
        info['code'] = 404
        info['message'] = '\n'.join([x[0] for x in msg])
        return Response(info, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        info = {
            'code': 200,
            'message': '删除成功',
            'data': []
        }
        return Response(info)


class ReasonPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'pageSize'
    page_query_param = 'pageNum'

    def get_paginated_response(self, data):
        info = {
            'code': 200,
            'message': '操作成功',
            'data': OrderedDict([
                ('list', data),
                ('pageNum', 1),
                ('pageSize', 10),
                ('total', self.page.paginator.count),
                ('totalPage', self.page.number)
            ]),

        }
        return Response(info)


class IndexCarouselGoodViewSet(CustomModelMixin, mixins.DestroyModelMixin):
    serializer_class = IndexCarouselGoodSerializer
    queryset = IndexCarouselGood.objects.all()
    pagination_class = ReasonPagination

    def get_serializer_class(self):
        if self.action == 'list':
            return ListCarouselGoodSerializer
        else:
            return IndexCarouselGoodSerializer


class GoodBrandViewSet(CustomModelMixin):
    serializer_class = GoodBrandSerializer
    queryset = GoodBrand.objects.all()
    pagination_class = ReasonPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['is_recommend']  # 精确查找


class ReturnReasonViewSet(CustomModelMixin):
    serializer_class = ReturnReasonSerializer
    queryset = ReturnReason.objects.all()
    pagination_class = ReasonPagination


class ReturnGoodViewSet(CustomModelMixin):
    serializer_class = ReturnAddressSerializer
    queryset = ReturnAddress.objects.all()


class SystemSetViewSet(CustomModelMixin):
    serializer_class = SystemSetSerializer
    queryset = SystemSet.objects.all()


class RolePagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'pageSize'
    page_query_param = 'page'

    def get_paginated_response(self, data):
        info = {
            'code': 200,
            'message': '操作成功',
            'data': OrderedDict([
                ('list', data),
            ]),

        }
        return Response(info)


class RoleListViewSet(CustomModelMixin):
    serializer_class = RoleListSerializer
    queryset = RoleList.objects.all()
    pagination_class = RolePagination

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        info = {
            'code': 200,
            'message': "操作成功",
            'data': [serializer.data]
        }
        return Response(info)


class MenuPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'pageSize'
    page_query_param = 'page'

    def get_paginated_response(self, data):
        info = {
            'code': 200,
            'message': '操作成功',
            'data': OrderedDict([
                ('username', 'admin'),
                ('roles', ["超级管理员"]),
                ('menus', data),
                ('icon', 'https://oscimg.oschina.net/oscnet/up-c31f4ed5767a5df9cd1f1b4afeb0139c33f.png')
            ]),

        }
        return Response(info)


class MenuListViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin,
                      viewsets.GenericViewSet):
    serializer_class = MenuListSerializer
    queryset = MenuList.objects.all()
    filter_backends = [DjangoFilterBackend]
    # filterset_fields = ['parentId']  # 精确查找
    filter_class = MenuFilter
    pagination_class = MenuPagination


class SuperGoodPagination(PageNumberPagination):
    page_size = 20
    max_page_size = 100
    page_size_query_param = 'pageSize'
    page_query_param = 'pageNum'


class ThirdGoodCategoryViewSet(ListAPIView, RetrieveModelMixin, UpdateModelMixin, viewsets.GenericViewSet):
    queryset = GoodCategory.objects.filter(category_type=3)
    serializer_class = SuperGoodCategorySerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({'code': 200, 'message': '操作成功', 'data': serializer.data})
        # return Response(serializer.data)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        # print(queryset)
        page = self.paginate_queryset(queryset)
        # print(page)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        pageNum = request.query_params.get('pageNum', 1)
        pageSize = request.query_params.get('pageSize', 5)
        serializer = self.get_serializer(queryset, many=True)
        # print(serializer.data)

        start = 0 if int(pageNum) == 1 else int(pageNum) - 1
        s = start * int(pageSize)
        e = (start * int(pageSize)) + int(pageSize)
        print(s, e)
        data = {
            'pageNum': int(pageNum),
            'pageSize': int(pageSize),
            'totalPage': math.ceil(queryset.count() / int(pageSize)),
            'total': queryset.count(),
            'list': serializer.data[s:e]
        }
        return Response({'code': 200, 'message': '操作成功', 'data': serializer.data})


class SecondGoodCategoryViewSet(ListAPIView, RetrieveModelMixin, UpdateModelMixin, viewsets.GenericViewSet):
    queryset = GoodCategory.objects.filter(category_type=1)
    serializer_class = SecondGoodCategorySerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({'code': 200, 'message': '操作成功', 'data': serializer.data})
        # return Response(serializer.data)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        # print(queryset)
        page = self.paginate_queryset(queryset)
        # print(page)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        pageNum = request.query_params.get('pageNum', 1)
        pageSize = request.query_params.get('pageSize', 5)
        serializer = self.get_serializer(queryset, many=True)
        # print(serializer.data)

        start = 0 if int(pageNum) == 1 else int(pageNum) - 1
        s = start * int(pageSize)
        e = (start * int(pageSize)) + int(pageSize)
        print(s, e)
        data = {
            'pageNum': int(pageNum),
            'pageSize': int(pageSize),
            'totalPage': math.ceil(queryset.count() / int(pageSize)),
            'total': queryset.count(),
            'list': serializer.data[s:e]
        }
        return Response({'code': 200, 'message': '操作成功', 'data': serializer.data})


class SuperGoodCategoryViewSet(ListAPIView, RetrieveModelMixin, UpdateModelMixin, viewsets.GenericViewSet):
    queryset = GoodCategory.objects.filter(category_type=1)
    serializer_class = SuperGoodCategorySerializer
    pagination_class = ReasonPagination
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['parent_category']  # 精确查找

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({'code': 200, 'message': '操作成功', 'data': serializer.data})
        # return Response(serializer.data)

    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # print(queryset)
    #     page = self.paginate_queryset(queryset)
    #     # print(page)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return self.get_paginated_response(serializer.data)
    #     pageNum = request.query_params.get('pageNum', 1)
    #     pageSize = request.query_params.get('pageSize', 5)
    #     serializer = self.get_serializer(queryset, many=True)
    #     # print(serializer.data)
    #
    #     start = 0 if int(pageNum) == 1 else int(pageNum) - 1
    #     s = start * int(pageSize)
    #     e = (start * int(pageSize)) + int(pageSize)
    #     print(s, e)
    #     data = {
    #         'pageNum': int(pageNum),
    #         'pageSize': int(pageSize),
    #         'totalPage': math.ceil(queryset.count() / int(pageSize)),
    #         'total': queryset.count(),
    #         'list': serializer.data[s:e]
    #     }
    #     return Response({'code': 200, 'message': '操作成功', 'data': data})


# class UserSerializers(serializers.Serializer):
#     # 获取 UserInfo 表的 user_type 字段的 key
#     # 变量名是任意取的，因为通过 source 指定了字段
#     user_type_id = serializers.CharField(source="user_type")
#     # 获取 UserInfo 表的 user_type 字段的 value
#     user_type_title = serializers.CharField(source="get_user_type_display")
#     # 获取 UserInfo 表的 username 和 password 字段
#     username = serializers.CharField()
#     password = serializers.CharField()
#     # 获取 UserInfo 表关联的 UserGroup 表的 title 字段（一对多的关系）
#     user_group = serializers.CharField(source="group.title")
#
#     # 获取 UserInfo 表关联的 Role 表的 id、title 字段（多对多关系）
#     user_role = serializers.SerializerMethodField()
#
#     # 命名规则：get_变量名，user_obj 为 user 对象
#     def get_user_role(self, user_obj):
#         role_list = user_obj.roles.all()
#         ret = []
#         # 获取 Role 表中的数据
#         for item in role_list:
#             ret.append({"id": item.id, "title": item.title})
#         return ret
#
#
# class UserInfoView(APIView):
#     def get(self, request, *args, **kwargs):
#         users = Good.objects.all()
#         ser = UserSerializers(instance=users, many=True)
#         ret = json.dumps(ser.data, ensure_ascii=False)
#         print(ret)
#         return HttpResponse(ret)


# class SuperGoodListViewSetTest(APIView):
#     def get(self, request, *args, **kwargs):
#         users = Good.objects.all()
#         ser = SuperGoodSerializer(instance=users, many=True)
#         ret = json.dumps(ser.data, ensure_ascii=False)
#         print(ret)
#         return HttpResponse(ret)

class ManageGoodPagination(PageNumberPagination):
    page_size = 20
    page_size_query_param = 'pageSize'
    page_query_param = 'pageNum'
    max_page_size = 50

    def get_paginated_response(self, data):
        print(self.page.paginator)
        info = {
            'code': 200,
            'message': '操作成功',
            'data': OrderedDict([
                ('list', data),
                ('pageNum', self.page.number),
                ('pageSize', self.page.paginator.per_page),
                ('total', self.page.paginator.count),
                ('totalPage', self.page.paginator.num_pages)
            ]),

        }
        return Response(info)


class SuperGoodListViewSet(ListModelMixin, RetrieveModelMixin, viewsets.GenericViewSet):
    throttle_classes = (AnonRateThrottle, UserRateThrottle)
    # .order_by('sold_num')
    queryset = Product.objects.all().order_by('id')
    serializer_class = SuperGoodSerializer
    pagination_class = ManageGoodPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    # search_fields = ['name']
    filterset_fields = ['sn', 'status', 'source', 'status']
    filter_class = SuperGoodFilter
    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # print(queryset)
    #     page = self.paginate_queryset(queryset)
    #     # print(page)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return self.get_paginated_response(serializer.data)
    #     pageNum = request.query_params.get('pageNum', 1)
    #     pageSize = request.query_params.get('pageSize', 5)
    #     serializer = self.get_serializer(queryset, many=True)
    #     # print(serializer.data)
    #     start = 0 if int(pageNum) == 1 else int(pageNum) - 1
    #     s = start * int(pageSize)
    #     e = (start * int(pageSize)) + int(pageSize)
    #     print(s, e)
    #     data = {
    #         'pageNum': int(pageNum),
    #         'pageSize': int(pageSize),
    #         'totalPage': math.ceil(queryset.count() / int(pageSize)),
    #         'total': queryset.count(),
    #         'list': serializer.data[s:e]
    #     }
    #     return Response({'code': 200, 'message': '操作成功', 'data': data})


def global_logout(request):
    if request.method == 'GET':
        info = {"code": 200, "message": "操作成功", "data": None}
        return JsonResponse(info)
    if request.method == 'POST':
        info = {"code": 200, "message": "操作成功", "data": None}
        return JsonResponse(info)


def global_login(request):
    if request.method == 'POST':
        # print(request.body)
        print(json.loads(request.body.decode()))
        # return JsonResponse({"code": 500, "message": "用户名或密码不正确", "data": None})
        if json.loads(request.body.decode()).get('username') != 'admin':
            return JsonResponse({"code": 500, "message": "用户名或密码不正确", "data": None})
        elif json.loads(request.body.decode()).get('username') == 'admin' and json.loads(request.body.decode()).get(
                'password') == '416798':
            return JsonResponse({"code": 200, "message": "操作成功", "data": {"tokenHead": "Bearer ",
                                                                          "token": ""}})
        else:
            return JsonResponse({"code": 500, "message": "用户名或密码不正确", "data": None})


def member(request):
    # memberLevel/list
    info = {"code": 200, "message": "操作成功", "data": [
        {"id": 1, "name": "黄金会员", "growthPoint": 1000, "defaultStatus": 0, "freeFreightPoint": 199.00,
         "commentGrowthPoint": 5, "priviledgeFreeFreight": 1, "priviledgeSignIn": 1, "priviledgeComment": 1,
         "priviledgePromotion": 1, "priviledgeMemberPrice": 1, "priviledgeBirthday": 1, "note": None},
        {"id": 2, "name": "白金会员", "growthPoint": 5000, "defaultStatus": 0, "freeFreightPoint": 99.00,
         "commentGrowthPoint": 10, "priviledgeFreeFreight": 1, "priviledgeSignIn": 1, "priviledgeComment": 1,
         "priviledgePromotion": 1, "priviledgeMemberPrice": 1, "priviledgeBirthday": 1, "note": None},
        {"id": 3, "name": "钻石会员", "growthPoint": 15000, "defaultStatus": 0, "freeFreightPoint": 69.00,
         "commentGrowthPoint": 15, "priviledgeFreeFreight": 1, "priviledgeSignIn": 1, "priviledgeComment": 1,
         "priviledgePromotion": 1, "priviledgeMemberPrice": 1, "priviledgeBirthday": 1, "note": None}]}
    return JsonResponse(info)


def global_info(request):
    info = {"code": 200, "message": "操作成功", "data": {"roles": ["超级管理员"],
                                                     "icon": "http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180607/timg.jpg",
                                                     "menus": [{"id": 1, "parentId": 0,
                                                                "createTime": "2020-02-02T06:50:36.000+00:00",
                                                                "title": "商品管理", "level": 0, "sort": 0, "name": "pms",
                                                                "icon": "product", "hidden": 0},
                                                               {"id": 2, "parentId": 1,
                                                                "createTime": "2020-02-02T06:51:50.000+00:00",
                                                                "title": "商品列表", "level": 1, "sort": 0,
                                                                "name": "product", "icon": "product-list", "hidden": 0},
                                                               {"id": 3, "parentId": 1,
                                                                "createTime": "2020-02-02T06:52:44.000+00:00",
                                                                "title": "添加商品", "level": 1, "sort": 0,
                                                                "name": "addProduct", "icon": "product-add",
                                                                "hidden": 0}, {"id": 4, "parentId": 1,
                                                                               "createTime": "2020-02-02T06:53:51.000+00:00",
                                                                               "title": "商品分类", "level": 1, "sort": 0,
                                                                               "name": "productCate",
                                                                               "icon": "product-cate", "hidden": 0},
                                                               {"id": 5, "parentId": 1,
                                                                "createTime": "2020-02-02T06:54:51.000+00:00",
                                                                "title": "商品类型", "level": 1, "sort": 0,
                                                                "name": "productAttr", "icon": "product-attr",
                                                                "hidden": 0}, {"id": 6, "parentId": 1,
                                                                               "createTime": "2020-02-02T06:56:29.000+00:00",
                                                                               "title": "品牌管理", "level": 1, "sort": 0,
                                                                               "name": "brand", "icon": "product-brand",
                                                                               "hidden": 0}, {"id": 7, "parentId": 0,
                                                                                              "createTime": "2020-02-02T08:54:07.000+00:00",
                                                                                              "title": "订单管理",
                                                                                              "level": 0,
                                                                                              "sort": 0, "name": "oms",
                                                                                              "icon": "order",
                                                                                              "hidden": 0},
                                                               {"id": 8, "parentId": 7,
                                                                "createTime": "2020-02-02T08:55:18.000+00:00",
                                                                "title": "订单列表", "level": 1, "sort": 0, "name": "order",
                                                                "icon": "product-list", "hidden": 0},
                                                               {"id": 9, "parentId": 7,
                                                                "createTime": "2020-02-02T08:56:46.000+00:00",
                                                                "title": "订单设置", "level": 1, "sort": 0,
                                                                "name": "orderSetting", "icon": "order-setting",
                                                                "hidden": 0}, {"id": 10, "parentId": 7,
                                                                               "createTime": "2020-02-02T08:57:39.000+00:00",
                                                                               "title": "退货申请处理", "level": 1, "sort": 0,
                                                                               "name": "returnApply",
                                                                               "icon": "order-return", "hidden": 0},
                                                               {"id": 11, "parentId": 7,
                                                                "createTime": "2020-02-02T08:59:40.000+00:00",
                                                                "title": "退货原因设置", "level": 1, "sort": 0,
                                                                "name": "returnReason", "icon": "order-return-reason",
                                                                "hidden": 0}, {"id": 12, "parentId": 0,
                                                                               "createTime": "2020-02-04T08:18:00.000+00:00",
                                                                               "title": "营销", "level": 0, "sort": 0,
                                                                               "name": "sms", "icon": "sms",
                                                                               "hidden": 0}, {"id": 13, "parentId": 12,
                                                                                              "createTime": "2020-02-04T08:19:22.000+00:00",
                                                                                              "title": "秒杀活动列表",
                                                                                              "level": 1, "sort": 0,
                                                                                              "name": "flash",
                                                                                              "icon": "sms-flash",
                                                                                              "hidden": 0},
                                                               {"id": 14, "parentId": 12,
                                                                "createTime": "2020-02-04T08:20:16.000+00:00",
                                                                "title": "优惠券列表", "level": 1, "sort": 0,
                                                                "name": "coupon", "icon": "sms-coupon", "hidden": 0},
                                                               {"id": 16, "parentId": 12,
                                                                "createTime": "2020-02-07T08:22:38.000+00:00",
                                                                "title": "品牌推荐", "level": 1, "sort": 0,
                                                                "name": "homeBrand", "icon": "product-brand",
                                                                "hidden": 0}, {"id": 17, "parentId": 12,
                                                                               "createTime": "2020-02-07T08:23:14.000+00:00",
                                                                               "title": "新品推荐", "level": 1, "sort": 0,
                                                                               "name": "homeNew", "icon": "sms-new",
                                                                               "hidden": 0}, {"id": 18, "parentId": 12,
                                                                                              "createTime": "2020-02-07T08:26:38.000+00:00",
                                                                                              "title": "人气推荐",
                                                                                              "level": 1, "sort": 0,
                                                                                              "name": "homeHot",
                                                                                              "icon": "sms-hot",
                                                                                              "hidden": 0},
                                                               {"id": 19, "parentId": 12,
                                                                "createTime": "2020-02-07T08:28:16.000+00:00",
                                                                "title": "专题推荐", "level": 1, "sort": 0,
                                                                "name": "homeSubject", "icon": "sms-subject",
                                                                "hidden": 0}, {"id": 20, "parentId": 12,
                                                                               "createTime": "2020-02-07T08:28:42.000+00:00",
                                                                               "title": "广告列表", "level": 1, "sort": 0,
                                                                               "name": "homeAdvertise",
                                                                               "icon": "sms-ad", "hidden": 0},
                                                               {"id": 21, "parentId": 0,
                                                                "createTime": "2020-02-07T08:29:13.000+00:00",
                                                                "title": "用户管理", "level": 0, "sort": 0, "name": "ums",
                                                                "icon": "ums", "hidden": 0}, {"id": 22, "parentId": 21,
                                                                                              "createTime": "2020-02-07T08:29:51.000+00:00",
                                                                                              "title": "用户列表",
                                                                                              "level": 1, "sort": 0,
                                                                                              "name": "admin",
                                                                                              "icon": "ums-admin",
                                                                                              "hidden": 0},
                                                               {"id": 23, "parentId": 21,
                                                                "createTime": "2020-02-07T08:30:13.000+00:00",
                                                                "title": "角色列表", "level": 1, "sort": 0, "name": "role",
                                                                "icon": "ums-role", "hidden": 0},
                                                               {"id": 24, "parentId": 21,
                                                                "createTime": "2020-02-07T08:30:53.000+00:00",
                                                                "title": "菜单列表", "level": 1, "sort": 0, "name": "menu",
                                                                "icon": "ums-menu", "hidden": 0},
                                                               {"id": 25, "parentId": 21,
                                                                "createTime": "2020-02-07T08:31:13.000+00:00",
                                                                "title": "资源列表", "level": 1, "sort": 0,
                                                                "name": "resource", "icon": "ums-resource",
                                                                "hidden": 0}], "username": "admin"}}
    return JsonResponse(info)


# productCategory/update/showStatus
def update_status(request):
    if request.method == 'POST':
        ids = request.POST.get('ids')
        gc = GoodCategory.objects.get(id=ids)
        judge = gc.is_display
        gc.is_display = 0 if judge == 1 else 1
        gc.save()
        info = {"code": 200, "message": "操作成功", "data": None}
        return JsonResponse(info)


# productCategory/update/navStatus
def update_nav(request):
    if request.method == 'POST':
        ids = request.POST.get('ids')
        gc = GoodCategory.objects.get(id=ids)
        judge = gc.is_banner
        gc.is_banner = 0 if judge == 1 else 1
        gc.save()
        info = {"code": 200, "message": "操作成功", "data": None}
        return JsonResponse(info)


import requests


def test_upload_file(request):
    info = {'name': 'foo.jpg',
            'url': 'https://oscimg.oschina.net/oscnet/up-32e7d729255f91dfcca64124ee1e31a9e3f.png'}

    if request.method == 'POST':
        file = request.FILES.get('file')
        #
        url = 'https://www.oschina.net/question/ckeditor_dialog_img_upload'

        headers = {
            "Host": "www.oschina.net",
            "Referer": "https://www.oschina.net/question/ask",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
            "Cookie": "__gads=ID=f5b00f1e4d17dc7b:T=1585900539:S=ALNI_MbQ8bB61a22zBX48VoN0qBUxQk7-Q; _user_behavior_=ecf5299b-32d4-49b5-81ab-abd857ab4c92; _reg_key_=w0eIoknWD5iFZr4tSGRk; yp_riddler_id=0e3792f3-03af-4f7b-8677-f6f195cdbad3; socialauth_id=RAg02HShkLqCPO8Lm433; _openid_key_=9a73e60f-2655-4795-8117-47e0906c37f3; Hm_lvt_a411c4d1664dd70048ee98afe7b28f0b=1593186715,1593187916,1593188000,1593188240; oscid=VEyPzQk6uUK1f61ugpczu37cWOooJrmzxI%2BoKvWSzxLlh6GBWKcMuo3KyuBI8Dq%2Bak1IYv2da%2FsGnQAGdLb0u%2Fzm2JkykyHjd8ZbQbU6WAvrGNOHKd%2F%2Blbx2D1kVhY7Ra4cH6mU1ZtM%3D; OSCHINA_SESSION=2625F8C96CFEA366241DBE80F45AA50F; ckCsrfToken=8pBPFKB5Wa6F2fJbaw7rWiyfzu5tJ2WC6GylAlL7; Hm_lpvt_a411c4d1664dd70048ee98afe7b28f0b=1593188414"
        }
        f = {'upload': (
            'logo.png', file, 'image/png')}
        rep = requests.post(url, files=f, headers=headers)
        print(rep.json())
        return JsonResponse(rep.json())
    else:
        return JsonResponse(info)
        # import requests


def update_cate(request):
    # /productCategory/update/
    if request.method == 'GET':
        info = {"code": 200, "message": "操作成功", "data": None}
        return JsonResponse(info)

    if request.method == 'POST':
        try:
            body = json.loads(request.body.decode())
            gc = GoodCategory.objects.get(id=body.get('id'))
            gc.name = body.get('name')
            gc.sort = body.get('sort')
            gc.save()
            info = {"code": 200, "message": "操作成功", "data": None}
            return JsonResponse(info)
        except:
            info = {"code": 500, "message": "排序值必须为阿拉伯数字", "data": None}
            return JsonResponse(info)


# /productCategory/list/withChildren
def withChildren(request):
    if request.method == 'GET':
        info = {"code": 200, "message": "操作成功", "data": [
            {"id": 1, "parentId": None, "name": "服装", "level": None, "productCount": None, "productUnit": None,
             "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None, "description": None,
             "children": [
                 {"id": 7, "parentId": None, "name": "外套", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 8, "parentId": None, "name": "T恤", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 9, "parentId": None, "name": "休闲裤", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 10, "parentId": None, "name": "牛仔裤", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 11, "parentId": None, "name": "衬衫", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 29, "parentId": None, "name": "男鞋", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None}]},
            {"id": 2, "parentId": None, "name": "手机数码", "level": None, "productCount": None, "productUnit": None,
             "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None, "description": None,
             "children": [
                 {"id": 19, "parentId": None, "name": "手机通讯", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 30, "parentId": None, "name": "手机配件", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 31, "parentId": None, "name": "摄影摄像", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 32, "parentId": None, "name": "影音娱乐", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 33, "parentId": None, "name": "数码配件", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 34, "parentId": None, "name": "智能设备", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None}]},
            {"id": 3, "parentId": None, "name": "家用电器", "level": None, "productCount": None, "productUnit": None,
             "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None, "description": None,
             "children": [
                 {"id": 35, "parentId": None, "name": "电视", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 36, "parentId": None, "name": "空调", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 37, "parentId": None, "name": "洗衣机", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 38, "parentId": None, "name": "冰箱", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 39, "parentId": None, "name": "厨卫大电", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 40, "parentId": None, "name": "厨房小电", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 41, "parentId": None, "name": "生活电器", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 42, "parentId": None, "name": "个护健康", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None}]},
            {"id": 4, "parentId": None, "name": "家具家装", "level": None, "productCount": None, "productUnit": None,
             "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None, "description": None,
             "children": [
                 {"id": 43, "parentId": None, "name": "厨房卫浴", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 44, "parentId": None, "name": "灯饰照明", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 45, "parentId": None, "name": "五金工具", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 46, "parentId": None, "name": "卧室家具", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 47, "parentId": None, "name": "客厅家具", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None}]},
            {"id": 5, "parentId": None, "name": "汽车用品", "level": None, "productCount": None, "productUnit": None,
             "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None, "description": None,
             "children": [
                 {"id": 48, "parentId": None, "name": "全新整车", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 49, "parentId": None, "name": "车载电器", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 50, "parentId": None, "name": "维修保养", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None},
                 {"id": 51, "parentId": None, "name": "汽车装饰", "level": None, "productCount": None, "productUnit": None,
                  "navStatus": None, "showStatus": None, "sort": None, "icon": None, "keywords": None,
                  "description": None}]}]}

        return JsonResponse(info)


# product/create
def create(request):
    info = {"code": 200, "message": "操作成功", "data": []}
    return JsonResponse(info)


# subject/listAll
def listAll(request):
    info = {"code": 200, "message": "操作成功", "data": [
        {"id": 1, "categoryId": 1, "title": "polo衬衫的也时尚", "pic": None, "productCount": None, "recommendStatus": None,
         "createTime": "2018-11-11T05:26:55.000+00:00", "collectCount": None, "readCount": None, "commentCount": None,
         "albumPics": None, "description": None, "showStatus": None, "forwardCount": None, "categoryName": "服装专题",
         "content": None},
        {"id": 2, "categoryId": 2, "title": "大牌手机低价秒", "pic": None, "productCount": None, "recommendStatus": None,
         "createTime": "2018-11-12T05:27:00.000+00:00", "collectCount": None, "readCount": None, "commentCount": None,
         "albumPics": None, "description": None, "showStatus": None, "forwardCount": None, "categoryName": "手机专题",
         "content": None},
        {"id": 3, "categoryId": 2, "title": "晓龙845新品上市", "pic": None, "productCount": None, "recommendStatus": None,
         "createTime": "2018-11-13T05:27:05.000+00:00", "collectCount": None, "readCount": None, "commentCount": None,
         "albumPics": None, "description": None, "showStatus": None, "forwardCount": None, "categoryName": "手机专题",
         "content": None},
        {"id": 4, "categoryId": 1, "title": "夏天应该穿什么", "pic": None, "productCount": None, "recommendStatus": None,
         "createTime": "2018-11-01T05:27:09.000+00:00", "collectCount": None, "readCount": None, "commentCount": None,
         "albumPics": None, "description": None, "showStatus": None, "forwardCount": None, "categoryName": "服装专题",
         "content": None},
        {"id": 5, "categoryId": 1, "title": "夏季精选", "pic": None, "productCount": None, "recommendStatus": None,
         "createTime": "2018-11-06T05:27:18.000+00:00", "collectCount": None, "readCount": None, "commentCount": None,
         "albumPics": None, "description": None, "showStatus": None, "forwardCount": None, "categoryName": "服装专题",
         "content": None},
        {"id": 6, "categoryId": 2, "title": "品牌手机降价", "pic": None, "productCount": None, "recommendStatus": None,
         "createTime": "2018-11-07T05:27:21.000+00:00", "collectCount": None, "readCount": None, "commentCount": None,
         "albumPics": None, "description": None, "showStatus": None, "forwardCount": None, "categoryName": "手机专题",
         "content": None}]}
    return JsonResponse(info)


# productAttribute/category/list
def productAttribute(request):
    if request.method == 'GET':
        info = {"code": 200, "message": "操作成功", "data": {"pageNum": 1, "pageSize": 100, "totalPage": 1, "total": 8,
                                                         "list": [{"id": 1, "name": "服装-T恤", "attributeCount": 2,
                                                                   "paramCount": 5},
                                                                  {"id": 2, "name": "服装-裤装", "attributeCount": 2,
                                                                   "paramCount": 4},
                                                                  {"id": 3, "name": "手机数码-手机通讯", "attributeCount": 2,
                                                                   "paramCount": 4},
                                                                  {"id": 4, "name": "配件", "attributeCount": 0,
                                                                   "paramCount": 0},
                                                                  {"id": 5, "name": "居家", "attributeCount": 0,
                                                                   "paramCount": 0},
                                                                  {"id": 6, "name": "洗护", "attributeCount": 0,
                                                                   "paramCount": 0},
                                                                  {"id": 10, "name": "测试分类", "attributeCount": 0,
                                                                   "paramCount": 0},
                                                                  {"id": 11, "name": "服装-鞋帽", "attributeCount": 3,
                                                                   "paramCount": 0}]}}

        return JsonResponse(info)


# returnReason/list
def returnReason(request):
    info = {"code": 200, "message": "操作成功", "data": {"pageNum": 1, "pageSize": 5, "totalPage": 2, "total": 9, "list": [
        {"id": 1, "name": "质量问题", "sort": 1, "status": 1, "createTime": "2018-10-17T02:00:45.000+00:00"},
        {"id": 2, "name": "尺码太大", "sort": 1, "status": 1, "createTime": "2018-10-17T02:01:03.000+00:00"},
        {"id": 3, "name": "颜色不喜欢", "sort": 1, "status": 1, "createTime": "2018-10-17T02:01:13.000+00:00"},
        {"id": 4, "name": "7天无理由退货", "sort": 1, "status": 1, "createTime": "2018-10-17T02:01:47.000+00:00"},
        {"id": 5, "name": "价格问题", "sort": 1, "status": 0, "createTime": "2018-10-17T02:01:57.000+00:00"}]}}
    return JsonResponse(info)


# role/listAll
def role(request):
    info = {"code": 200, "message": "操作成功", "data": [
        {"id": 1, "name": "商品管理员", "description": "只能查看及操作商品", "adminCount": 0,
         "createTime": "2020-02-03T08:50:37.000+00:00", "status": 1, "sort": 0},
        {"id": 2, "name": "订单管理员", "description": "只能查看及操作订单", "adminCount": 0,
         "createTime": "2018-09-30T07:53:45.000+00:00", "status": 1, "sort": 0},
        {"id": 5, "name": "超级管理员", "description": "拥有所有查看和操作功能", "adminCount": 0,
         "createTime": "2020-02-02T07:11:05.000+00:00", "status": 1, "sort": 0}]}

    return JsonResponse(info)


# role/list
def role_list(request):
    info = {"code": 200, "message": "操作成功", "data": {"pageNum": 1, "pageSize": 5, "totalPage": 1, "total": 3, "list": [
        {"id": 1, "name": "商品管理员", "description": "只能查看及操作商品", "adminCount": 0,
         "createTime": "2020-02-03T08:50:37.000+00:00", "status": 1, "sort": 0},
        {"id": 2, "name": "订单管理员", "description": "只能查看及操作订单", "adminCount": 0,
         "createTime": "2018-09-30T07:53:45.000+00:00", "status": 1, "sort": 0},
        {"id": 3, "name": "营销管理员", "description": "只能查看及营销操作", "adminCount": 0,
         "createTime": "2018-09-30T07:53:45.000+00:00", "status": 1, "sort": 0},
        {"id": 4, "name": "超级管理员", "description": "拥有所有查看和操作功能", "adminCount": 0,
         "createTime": "2020-02-02T07:11:05.000+00:00", "status": 1, "sort": 0}]}}
    return JsonResponse(info)
